package com.zm.demo.core.concurrent;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

import static java.lang.System.err;
import static java.lang.System.out;

/**
 * @author zoum
 * @create 2019/6/18 18:00
 */
public class ExecutorsDemo {

    public static void main(String[]args) throws Exception{


        ExecutorService executorService = Executors.newFixedThreadPool(8);
        List<Callable<Integer>> callables = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            final int j = i;
            Callable<Integer> callable = (() -> {
                Thread.sleep(1000);
//                if (80 == j){
//                    out.println("interrupted: " + j);
//                    Thread.currentThread().interrupt();
//                }
                out.println(Thread.currentThread().getName() + "========> " + System.currentTimeMillis());
                return j;
            });
            callables.add(callable);
        }
//
        err.println("before == " + System.currentTimeMillis() + " " + callables.size());
//        Integer future = executorService.invokeAny(callables);
        List<Future<Integer>> futures = executorService.invokeAll(callables);
        callables.clear();
        err.println("after == " + System.currentTimeMillis() + " " + callables.size());
//
//        Integer future = executorService.invokeAny(callables);
        List<Future<Integer>> futures1 = executorService.invokeAll(callables);
        err.println("after == " + System.currentTimeMillis() + " " + callables.size());
//

    }

    @Test
    public void testCachePool(){
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 100 ; i++) {
            executorService.submit(() -> {
                out.println(Thread.currentThread().getName() + "--" );
                try {
                    Thread.sleep(50L);
                }catch (Exception e){
                    e.printStackTrace();
                }
            });
        }
    }
}
